<template>
  <div class="order">
    <el-card>
      <el-table :data="orderList" border style="width: 100%">
        <el-table-column type="expand">
          <template #default="props">
            <div class="order-detail">
              <div class="order-info">
                <p><strong>订单编号：</strong>{{ props.row.id }}</p>
                <p><strong>下单时间：</strong>{{ props.row.createTime }}</p>
                <p><strong>总金额：</strong>¥{{ (props.row.totalAmount / 100).toFixed(2) }}</p>
              </div>
              <div class="order-items">
                <h4>订单商品</h4>
                <el-table :data="props.row.items" border>
                  <el-table-column prop="medicineName" label="药品名称"></el-table-column>
                  <el-table-column prop="price" label="单价">
                    <template #default="scope">¥{{ scope.row.price }}</template>
                  </el-table-column>
                  <el-table-column prop="quantity" label="数量"></el-table-column>
                  <el-table-column label="小计">
                    <template #default="scope">
                      ¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="订单编号" width="180"></el-table-column>
        <el-table-column prop="createTime" label="下单时间" width="180"></el-table-column>
        <el-table-column prop="totalAmount" label="订单金额" width="120">
          <template #default="scope"> ¥{{ (scope.row.totalAmount / 100).toFixed(2) }} </template>
        </el-table-column>
        <el-table-column prop="orderStatus" label="订单状态" width="120">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.orderStatus)">
              {{ getStatusText(scope.row.orderStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button
              v-if="scope.row.orderStatus === 0"
              type="primary"
              size="small"
              @click="payOrder(scope.row)"
            >
              付款
            </el-button>
            <el-button
              v-if="scope.row.orderStatus === 2"
              type="success"
              size="small"
              @click="confirmReceive(scope.row)"
            >
              确认收货
            </el-button>
            <el-button
              v-if="scope.row.orderStatus === 0"
              type="danger"
              size="small"
              @click="cancelOrder(scope.row)"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
      ></el-pagination>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listOrder, updateOrder } from '@/api/order'
import { listItem } from '@/api/item'
import { listMedicine } from '@/api/medicine'

// 订单状态
const orderStatus = ref('')

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 订单列表
const orderList = ref([])

// 详情对话框
const dialogVisible = ref(false)
const currentOrder = ref(null)

// 获取订单列表
const getOrderList = async () => {
  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    const res = await listOrder()

    // 获取药品列表
    const medicineRes = await listMedicine()
    const medicineMap = {}
    medicineRes.data.forEach((medicine) => {
      medicineMap[medicine.id] = medicine
    })

    // 获取每个订单的商品列表
    const orders = await Promise.all(
      res.data.map(async (order) => {
        const itemRes = await listItem({ orderId: order.id })
        // 为每个订单项添加药品名称
        const items = itemRes.data.map((item) => {
          const medicine = medicineMap[item.medicineId] || {}
          return {
            ...item,
            medicineName: medicine.medicineName || '未知药品',
          }
        })
        return {
          ...order,
          items: items || [],
        }
      }),
    )

    orderList.value = orders
    total.value = res.total
  } catch (error) {
    console.error('获取订单列表失败', error)
    ElMessage.error('获取订单列表失败')
  }
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '待付款',
    1: '待发货',
    2: '已发货',
    3: '已完成',
    4: '已取消',
  }
  return statusMap[status] || '未知状态'
}

// 获取状态标签类型
const getStatusType = (status) => {
  const typeMap = {
    0: 'warning',
    1: 'primary',
    2: 'success',
    3: 'info',
    4: 'danger',
  }
  return typeMap[status] || ''
}

// 查看订单详情
const viewOrderDetail = (order) => {
  currentOrder.value = order
  dialogVisible.value = true
}

// 支付订单
const payOrder = (order) => {
  ElMessageBox.confirm(`确定要支付订单 ${order.id} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        // 调用API支付订单
        await updateOrder({
          id: order.id,
          orderStatus: 1, // 已支付，待发货
        })
        ElMessage.success('支付成功')
        getOrderList()
      } catch (error) {
        console.error('支付失败', error)
        ElMessage.error('支付失败')
      }
    })
    .catch(() => {})
}

// 确认收货
const confirmReceive = (order) => {
  ElMessageBox.confirm(`确定要确认收到订单 ${order.id} 的商品吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        // 调用API确认收货
        await updateOrder({
          id: order.id,
          orderStatus: 3, // 已完成
        })
        ElMessage.success('确认收货成功')
        getOrderList()
      } catch (error) {
        console.error('操作失败', error)
        ElMessage.error('操作失败')
      }
    })
    .catch(() => {})
}

// 取消订单
const cancelOrder = (order) => {
  ElMessageBox.confirm(`确定要取消订单 ${order.id} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        // 调用API取消订单
        await updateOrder({
          id: order.id,
          orderStatus: 4, // 已取消
        })
        ElMessage.success('订单已取消')
        getOrderList()
      } catch (error) {
        console.error('取消失败', error)
        ElMessage.error('取消失败')
      }
    })
    .catch(() => {})
}

// 页码变化
const handlePageChange = (page) => {
  currentPage.value = page
  getOrderList()
}

// 初始化
onMounted(() => {
  getOrderList()
})
</script>

<style scoped>
.order-detail {
  padding: 20px;
}

.order-info {
  margin-bottom: 20px;
}

.order-items {
  margin-top: 20px;
}

.order-items h4 {
  margin-bottom: 10px;
}
</style>
